package com.example.trb.controller.user;

import com.example.trb.dto.UserDTO;
import com.example.trb.entity.User;
import com.example.trb.service.user.UserService;
import com.example.trb.util.result.CommonResult;
import com.example.trb.util.result.UserReturnCode;
import com.example.trb.vo.LoginRegisterVO;
import com.example.trb.vo.UpdatePasswordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    UserService userService;
    @Value("${session_user}")
    String userKey;

    @PostMapping("/logout")
    public CommonResult logout(HttpSession session) {
        session.removeAttribute(userKey);
        return CommonResult.success(null);
    }

    @PutMapping("/user/password")
    public CommonResult updatePassword(
            @Validated @RequestBody UpdatePasswordVO vo,
            HttpSession session
    ) {
        UserDTO dto = userService.setPassword(vo);
        UserReturnCode code = dto.getCode();
        session.removeAttribute(userKey);
        return CommonResult.common(code.code, code.message, null);
    }

    @PostMapping("/user/register")
    public CommonResult register(@RequestBody @Validated LoginRegisterVO vo) {
        User user = new User(vo.getAccount(), vo.getPassword());
        UserDTO register = userService.register(user);

        UserReturnCode registerCode = register.getCode();
        if (registerCode == UserReturnCode.USER_EXIST) {
            return CommonResult.fail(registerCode.code, registerCode.message);
        }

        return CommonResult.success(register.getData());
    }

    @PostMapping("/user/login")
    public CommonResult login(
            @RequestBody @Validated LoginRegisterVO vo,
            HttpSession session
    ) {
        User user = new User(vo.getAccount(), vo.getPassword());
        UserDTO login = userService.login(user);

        UserReturnCode loginCode = login.getCode();
        if (loginCode == UserReturnCode.USER_NOT_EXIST) {
            return CommonResult.fail(loginCode.code, loginCode.message);
        }
        if (loginCode == UserReturnCode.PASSWORD_OR_ACCOUNT_ERROR) {
            return CommonResult.fail(loginCode.code, loginCode.message);
        }

        session.setAttribute(userKey, login.getData());
        return CommonResult.success(login.getData());
    }
}
